﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CreateTopic : System.Web.UI.Page
{


    #region PROPERTIES

    private UserCredentials User
    {
        get { return Session["user"] as UserCredentials; }
        set { Session["user"] = value; }
    }

    #endregion



    protected void Page_Load(object sender, EventArgs e)
    {

    }



    protected void CreateButton_Click(object sender, EventArgs e)
    {
        //TODO :: VALIDERAR LÄNGD OCH SANITIZAR TEXTEN, RÄCKER VÄL?
        Service service = new Service();
        Validation validation = new Validation();
        Sanitize sanitize = new Sanitize();


        if (validation.ValidateNewTopic(HeaderTextBox.Text, ContentTextbox.Text))
        {
            string sanitizedHeader = sanitize.EncodeText(HeaderTextBox.Text);
            string sanitizedContent = sanitize.EncodeText(ContentTextbox.Text);

            OneTopic topic = new OneTopic(User.UserID, sanitizedHeader, User.Username, sanitizedContent);
            service.SaveTopic(topic);
            List<string> successMessage = new List<string>();
            successMessage.Add("The topic has been created.");
            Session["successMessage"] = successMessage;
            Response.Redirect("~/Forum.aspx");
        }
        else
        {
            List<string> errormessages = validation.GetErrorMessages();

            if (errormessages != null)
            {
                foreach (string error in errormessages)
                {
                    AddErrorMessage(error);
                }
            }
        }
    }



    #region  AddErrorMessage

    private void AddErrorMessage(string message)
    {
        Validators.Add(new CustomValidator
        {
            ErrorMessage = message,
            IsValid = false
        });
    }

    private void AddErrorMessage(IDataErrorInfo obj)
    {
        obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .Where(n => !String.IsNullOrWhiteSpace(obj[n])) // vill bara ha de som inte är tomma.
            .ToList()  // gör om till lista.
            .ForEach(n => AddErrorMessage(obj[n]));  // loopar igenom namnen som återstår o lägger till.
    }

    #endregion

}